package com.example.common;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Dict;
import com.example.exception.CustomerException;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;

//处理文件上传下载的接口
@RestController
@RequestMapping("/files")
public class FileController {
    //上传文件
    @PostMapping("/upload")
    public Result upload(@RequestParam("file") MultipartFile file) throws Exception {
        //获取当前项目文件的绝对路径
        String filePath = System.getProperty("user.dir") + "/files/"; // 获取到当前项目文件的绝对路径 D:\vue3\code2025
        if(!FileUtil.isDirectory(filePath)){
            FileUtil.mkdir(filePath);
        }
        byte[] bytes = file.getBytes();
        String fileName = System.currentTimeMillis() + "-" + file.getOriginalFilename(); // 获取到上传文件的原始名称

        // 创建一个文件对象，用于保存上传的文件
        FileUtil.writeBytes(bytes, filePath  + fileName);
        String url = "http://localhost:9999/files/download/" + fileName;
        return Result.success(url);
    }
    //处理文件下载的接口 下载路径 http://localhost:9999/files/download/bj.jpg
    @GetMapping("/download/{fileName}")
    public void download(@PathVariable String fileName, HttpServletResponse response) throws Exception {
        //获取当前项目文件的绝对路径
        String filePath = System.getProperty("user.dir") + "/files/"; // 获取到当前项目文件的绝对路径 D:\vue3\code2025
        String realPath = filePath + fileName; // 获取到当前项目文件的绝对路径 D:\vue3\code2025\files\bj.jpg
        boolean exist = FileUtil.exist(realPath);
        if (!exist) {
            throw new CustomerException("请求的文件 ");
        }
        //  读取文件
        byte[] bytes = FileUtil.readBytes(realPath);
        ServletOutputStream os = response.getOutputStream();
        // 输出流对象把文件写入到浏览器
        os.write(bytes);
        os.flush();
        os.close();
    }
    //处理富文本上传的接口
    @PostMapping("wang/upload")
    public Map<String, Object> wangEditorUpload(MultipartFile file) {
        String flag = System.currentTimeMillis() + "";
        String fileName = file.getOriginalFilename();
        try {
            String filePath = System.getProperty("user.dir") + "/files/";
            // 文件储存形式：时间戳-文件名
            FileUtil.writeBytes(file.getBytes(), filePath + flag + "-" + fileName);
            System.out.println(fileName +  "文件上传成功");
            Thread.sleep(1L);
        } catch (Exception e) {
            System.out.println(fileName +  "文件上传失败");
        }
        String http = "http://localhost:9999/files/download/";
        Map<String, Object> resMap = new HashMap<>();
        // wangEditor 上传图片成功后， 需要返回的参数
        resMap.put("errno", 0);
        resMap.put("data", CollUtil.newArrayList(Dict.create().set("url", http + flag + "-" + fileName)));
        return resMap;
    }
}
